import React, {useState} from 'react';
import {
    Button,
    Dropdown,
    Input,
    Menu,
    Select,
    Table,
    Tag,
    Upload,
} from 'antd';
import {
    UploadOutlined,
    SearchOutlined,
    DownloadOutlined,
    FilterOutlined,
} from '@ant-design/icons';

import {v4 as uuidv4} from 'uuid';
import * as XLSX from 'xlsx';
import {Document, Packer, Paragraph, TextRun} from 'docx';
import {saveAs} from 'file-saver';

const IvySciNotesTools = () => {
    const [data, setData] = useState([]);
    const [filters, setFilters] = useState({
        fileName: '',
        text: '',
        notes: '',
        type: '',
        tags: [],
    });
    //唯一标签数组
    const allTags = Array.from(new Set(data.flatMap(row => row.tags)));

    const handleFilterChange = (field, value) => {
        setFilters(prevFilters => ({
            ...prevFilters,
            [field]: value,
        }));
    };

    const randomColor = () => {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    };
    const colorToType = color => {
        switch (color) {
            case '#ffd400':
                return '专有名词';
            case '#ff4d4f':
                return '论点观点';
            case '#1890ff':
                return '总结';
            case '#52c41a':
                return '引用、推理或代码';
            default:
                return '未知类型';
        }
    };

    const columns = [
        {
            title: '文献名称',
            dataIndex: 'fileName',
            key: 'fileName',
            width: 200,
        },
        {
            title: '文本',
            dataIndex: 'text',
            key: 'text',
            width: 200,
        },
        {
            title: '笔记',
            dataIndex: 'notes',
            key: 'notes',
            width: 400,
        },
        {
            title: '类型',
            dataIndex: 'color',
            key: 'color',
            width: 100,
            render: color => (
                <>
                    <div
                        style={{
                            display: 'inline-block',
                            width: '16px',
                            height: '16px',
                            backgroundColor: color,
                            marginRight: '8px',
                        }}></div>
                    {colorToType(color)}
                </>
            ),
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags',
            width: 100,
            render: tags => (
                <>
                    {tags.map(tag => (
                        <Tag
                            key={tag}
                            color={randomColor()}>
                            {tag}
                        </Tag>
                    ))}
                </>
            ),
        },
    ];

    const processData = file => {
        const reader = new FileReader();
        reader.onload = e => {
            const result = JSON.parse(e.target.result);
            const parsedData = result.map(entry =>
                entry.highlights.map(highlight => ({
                    key: uuidv4(),
                    fileName: entry.file.file_name,
                    text: highlight.text,
                    notes: highlight.notes,
                    color: highlight.color,
                    tags: highlight.tags,
                }))
            );
            setData(parsedData.flat());
        };
        reader.readAsText(file);
        return false;
    };

    const exportExcel = () => {
        const header = ['文献名称', '文本', '笔记', '类型', '标签'];
        const ws_data = [
            header,
            ...data.map(row => [
                row.fileName,
                row.text,
                row.notes,
                colorToType(row.color),
                row.tags.join(', '),
            ]),
        ];

        const ws = XLSX.utils.aoa_to_sheet(ws_data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'IvySciNotes');

        XLSX.writeFile(wb, 'IvySciNotes.xlsx');
    };

    const exportWord = async () => {
        const doc = new Document();

        const children = [];

        data.forEach(row => {
            const type = colorToType(row.color);
            const tags = row.tags.join(', ');
            children.push(
                new Paragraph({
                    children: [
                        new TextRun(`文献名称: ${row.fileName}`),
                        new TextRun('\n'),
                        new TextRun(`文本: ${row.text}`),
                        new TextRun('\n'),
                        new TextRun(`笔记: ${row.notes}`),
                        new TextRun('\n'),
                        new TextRun(`类型: ${type}`),
                        new TextRun('\n'),
                        new TextRun(`标签: ${tags}`),
                    ],
                })
            );
            children.push(new Paragraph({children: [new TextRun('\n')]}));
        });

        doc.addSection({children});

        const buffer = await Packer.toBuffer(doc);
        const blob = new Blob([buffer], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        });
        saveAs(blob, 'IvySciNotes.docx');
    };

    const menu = (
        <Menu>
            <Menu.Item
                key='1'
                onClick={exportExcel}>
                导出 Excel
            </Menu.Item>
            <Menu.Item
                key='2'
                onClick={exportWord}>
                导出 Word
            </Menu.Item>
        </Menu>
    );
    const filterContent = (
        <div>
            <Input
                placeholder='论文名称'
                prefix={<SearchOutlined/>}
                value={filters.fileName}
                onChange={e => handleFilterChange('fileName', e.target.value)}
                style={{marginBottom: 8}}
            />
            <Input
                placeholder='文本'
                prefix={<SearchOutlined/>}
                value={filters.text}
                onChange={e => handleFilterChange('text', e.target.value)}
                style={{marginBottom: 8}}
            />
            <Input
                placeholder='笔记'
                prefix={<SearchOutlined/>}
                value={filters.notes}
                onChange={e => handleFilterChange('notes', e.target.value)}
                style={{marginBottom: 8}}
            />
            <Select
                placeholder='类型'
                value={filters.type}
                onChange={value => handleFilterChange('type', value)}
                style={{width: '100%', marginBottom: 8}}>
                <Select.Option value=''>所有类型</Select.Option>
                <Select.Option value='#ffd400'>专有名词</Select.Option>
                <Select.Option value='#ff4d4f'>论点观点</Select.Option>
                <Select.Option value='#40a9ff'>总结</Select.Option>
                <Select.Option value='#73d13d'>推理、公式或代码</Select.Option>
            </Select>
            <Select
                mode='multiple'
                placeholder='标签'
                value={filters.tags}
                onChange={value => handleFilterChange('tags', value)}
                style={{width: '100%'}}>
                {allTags.map(tag => (
                    <Select.Option
                        key={tag}
                        value={tag}>
                        {tag}
                    </Select.Option>
                ))}
            </Select>
        </div>
    );

    return (
        <div>
            <Upload
                accept='.json'
                beforeUpload={processData}
                showUploadList={false}>
                <Button icon={<UploadOutlined/>}>导入</Button>
            </Upload>
            <Dropdown overlay={menu}>
                <Button icon={<DownloadOutlined/>}>
                    导出 <span style={{fontSize: '12px'}}>▼</span>
                </Button>
            </Dropdown>
            <Dropdown overlay={filterContent}>
                <Button
                    icon={<FilterOutlined/>}
                    style={{marginLeft: 8}}>
                    筛选
                </Button>
            </Dropdown>
            <Table
                columns={columns}
                dataSource={data.filter(row => {
                    const fileNameMatch = row.fileName
                        .toLowerCase()
                        .includes(filters.fileName.toLowerCase());
                    const textMatch = row.text
                        .toLowerCase()
                        .includes(filters.text.toLowerCase());
                    const notesMatch = row.notes
                        .toLowerCase()
                        .includes(filters.text.toLowerCase());
                    const typeMatch = filters.type === '' || row.color === filters.type;
                    const tagsMatch = filters.tags.every(tag => row.tags.includes(tag));

                    return (
                        fileNameMatch && textMatch && typeMatch && tagsMatch && notesMatch
                    );
                })}
            />
        </div>
    );
};

export default IvySciNotesTools;
